/**
 * Copyright (C) 2013-2014 the original author or authors.
 */
package com.foreveross.bsl.auth.support.servlet.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.foreveross.bsl.auth.constant.Constant;
import com.foreveross.bsl.auth.integration.ChannelIntegration;
import com.foreveross.bsl.auth.integration.ChannelIntegrationBuilder;
import com.foreveross.bsl.common.utils.context.ContextThead;

/**
 * @description
 *
 * @author rening
 * @version v1.0
 *
 * @2013-8-9
 *
 */
public class TicketFilter extends CommonFilter {

	private Logger log = LoggerFactory.getLogger(TicketFilter.class);

	protected String getTicket(HttpServletRequest httpServletRequest) {
		String ticket = (String)httpServletRequest.getSession().getAttribute(Constant.SESSION_KEY);
		return ticket;
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		ChannelIntegration ticketChannelIntegration = ChannelIntegrationBuilder.newInstance();
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		
		/**check the request */
		if(checkPass(httpServletRequest)){
			chain.doFilter(httpServletRequest, httpServletResponse);
		} else {
			String ticket = getTicket(httpServletRequest);
			String redirector = httpServletRequest.getContextPath() + "/system/account/login-view";
			if(StringUtils.isBlank(ticket)){
				httpServletResponse.sendRedirect(redirector);
				return;
			}

			Map parameters = getParameters(httpServletRequest);
			boolean validate = true;
			try {
				ContextThead.setThreadSessionKey(ticket); // 自己这条线程的作用域
				validate = ticketChannelIntegration.validateIdentity(ticket, parameters);
			} catch (Exception e) {
				log.error(e.getMessage(), e);
//				httpServletResponse.sendError(ErrorCode.SYSTEM_UNKNOWN, ErrorCode.message(ErrorCode.SYSTEM_UNKNOWN));
				httpServletResponse.sendRedirect(redirector);
				return;
			}
			if (validate) {
				chain.doFilter(request, response);
			} else {
//				httpServletResponse.sendError(ErrorCode.SYSTEM_AUTH_ERROR, ErrorCode.message(ErrorCode.SYSTEM_AUTH_ERROR));
				httpServletResponse.sendRedirect(redirector);
				return;
			}
		}
	}

}
